package com.cxs.plan.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxs.plan.DTO.BillDTO;
import com.cxs.plan.VO.FilterUserVO;
import com.cxs.plan.domain.entity.Bill;
import com.cxs.plan.domain.entity.UserWithBill;
import com.cxs.plan.mapper.UserWithBillMapper;
import com.cxs.plan.service.BillService;
import com.cxs.plan.mapper.BillMapper;
import com.cxs.plan.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
* @author Administrator
* @description 针对表【bill(账单)】的数据库操作Service实现
* @createDate 2024-03-28 15:41:37
*/
@Service
public class BillServiceImpl extends ServiceImpl<BillMapper, Bill>
    implements BillService{
    @Autowired
    private  BillMapper billMapper;

    @Autowired
    private UserWithBillMapper userWithBillMapper;

    @Override
    public List<Bill> getBillList() {
        return billMapper.getBillListByUserId(BaseContext.getCurrentId());
    }

    @Transactional
    @Override
    public void saveBill(BillDTO billDTO) {
        Integer userId = BaseContext.getCurrentId();
        billDTO.setUserId(userId);
        billMapper.insert(billDTO);
        UserWithBill userWithBill = new UserWithBill();
        userWithBill.setBillId(billDTO.getId());
        userWithBill.setUserId(userId);
        userWithBillMapper.insert(userWithBill);
        List<Integer> memberIds = billDTO.getMemberIds();
        if(!memberIds.isEmpty()) userWithBillMapper.insertBatch(memberIds, billDTO.getId());
    }

    @Transactional
    @Override
    public void deleteBillById(Integer id) {
        billMapper.deleteById(id);
    }

    @Override
    public Object getBillInfo(Integer billId) {
        Integer userId = BaseContext.getCurrentId();
        List<FilterUserVO> filterUserVOS = userWithBillMapper.selectByUserId(billId);
        Bill bill = billMapper.selectById(billId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", bill.getName());
        map.put("id", bill.getId());
        map.put("remark", bill.getRemark());
        map.put("userList", filterUserVOS);
        return map;
    }

    @Transactional
    @Override
    public void updateBill(BillDTO billDTO) {
        Integer userId = BaseContext.getCurrentId();
        billDTO.setUserId(userId);
        billMapper.updateById(billDTO);
        if(!billDTO.getMemberIds().isEmpty()) userWithBillMapper.insertBatch(billDTO.getMemberIds(), billDTO.getId());
    }
}




